package com.scw.hothot;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.XLog;
import com.elvishew.xlog.printer.Printer;
import com.elvishew.xlog.printer.file.FilePrinter;
import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class MainActivity extends Activity {

    private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";
    private static final String TAG = "@#@#";

    // UI部分
    Button button_init;
    Button button_read;
    Button button_newLog;
    EditText editText_filename;

    Button button_sendmessage1;
    Button button_sendmessage2;
    Button button_sendmessage3;

    EditText editText_message1;
    EditText editText_message2;
    EditText editText_message3;

    TextView textView_print;
    TextView textView_angle;
    TextView textView_angle2;
    EditText editTextNumber_datalength;
    EditText editTextNumber_dataindex;

    EditText editTextNumber_dataindex2;
    ImageView imageView_pointer;

    // USB
    UsbManager mUsbManager;
    UsbSerialDriver driver;
    UsbDeviceConnection connection;
    UsbSerialPort port;


    // 标志位
    boolean usb_connect = false;
    boolean save = false;

    Message msg = new Message();
    private Thread mReadingthread = null;

    StringBuffer print_Buffer = new StringBuffer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
        initXlog();
    }

    void initUI(){
        button_init = findViewById(R.id.button_init);
        button_init.setOnClickListener(v -> {
            try {
                run();
            } catch (IOException e) {
                Log.i(TAG, String.format("run %s",e));
                e.printStackTrace();
            }
        });
        button_read = findViewById(R.id.button_read);
        button_read.setOnClickListener(v-> {
            try {
                startReading();
            } catch (IOException e) {
                Log.i(TAG, String.format("startReading %s",e));
                e.printStackTrace();
            }
        });

        button_newLog = findViewById(R.id.button_newLog);
        button_newLog.setOnClickListener(v-> {
            newLog();
        });

        editText_filename = findViewById(R.id.editText_filename);

        editText_message1 = findViewById(R.id.editText_message1);
        button_sendmessage1 = findViewById(R.id.button_sendmessage1);
        button_sendmessage1.setOnClickListener(v -> {
            try {
                send(editText_message1.getText().toString());

            } catch (IOException e) {
                Log.i(TAG, String.format("Send1 %s",e));
                e.printStackTrace();
            }
        });

        editText_message2 = findViewById(R.id.editText_message2);
        button_sendmessage2 = findViewById(R.id.button_sendmessage2);
        button_sendmessage2.setOnClickListener(v -> {
            try {
                send(editText_message2.getText().toString());
            } catch (IOException e) {
                Log.i(TAG, String.format("Send2 %s",e));
                e.printStackTrace();
            }
        });

        editText_message3 = findViewById(R.id.editText_message3);
        button_sendmessage3 = findViewById(R.id.button_sendmessage3);
        button_sendmessage3.setOnClickListener(v -> {
            try {
                send(editText_message3.getText().toString());
            } catch (IOException e) {
                Log.i(TAG, String.format("Send3 %s",e));
                e.printStackTrace();
            }
        });

        textView_print = findViewById(R.id.textView_print);
        textView_angle = findViewById(R.id.textView_angle);
        textView_angle2 = findViewById(R.id.textView_angle2);
        editTextNumber_datalength = findViewById(R.id.editTextNumber_datalength);
        editTextNumber_dataindex = findViewById(R.id.editTextNumber_dataindex);

        editTextNumber_dataindex2 = findViewById(R.id.editTextNumber_dataindex2);
        imageView_pointer = findViewById(R.id.imageView_pointer);

//        Bitmap bg = ((BitmapDrawable) getResources().getDrawable(R.drawable.hello)).getBitmap();
//        Bitmap fg = ((BitmapDrawable) getResources().getDrawable(R.drawable.pointer)).getBitmap();
//        int bgWidth=bg.getWidth();
//        int bgHeight=bg.getHeight();
//        Log.i(TAG, String.format("bgWidth: %d",bgWidth));
//        Log.i(TAG, String.format("bgHeight: %d",bgHeight));
//        int fgWidth=fg.getWidth(); //前景图宽度，用于后面计算前景图的绘制坐标
//        //Bitmap newbmp=Bitmap.createBitmap(bgWidth,bgHeight,Bitmap.Config.RGB_565);
//        Bitmap newbmp=Bitmap.createBitmap(bgWidth,bgHeight,Bitmap.Config.RGB_565);
//        Canvas cv=new Canvas(newbmp);
////drawbginto
////在0，0坐标开始画入bg
//        cv.drawBitmap(bg,0,0,null);
////drawfginto
////开始画入fg，可以从任意位置画入，具体位置自己计算
//        cv.drawBitmap(fg,0,0,null);
//        int newbmpbgWidth=newbmp.getWidth();
//        int newbmpbgHeight=newbmp.getHeight();
//        Log.i(TAG, String.format("newbmpbgWidth: %d",newbmpbgWidth));
//        Log.i(TAG, String.format("newbmpbgHeight: %d",newbmpbgHeight));
//
//        Matrix matrix=new Matrix();
//        matrix.setScale(1,1);
//        Bitmap compbmp=Bitmap.createBitmap(newbmp,0,0,newbmp.getWidth(), newbmp.getHeight(),matrix,true);
//        imageView_pointer.setImageBitmap(bg);
    }

    void newLog(){
        String filename = editText_filename.getText().toString();
        if(!filename.isEmpty()){
            if(save){
                editText_filename.setText("");
                button_newLog.setText("创建日志");
                save = false;
            }else {
                button_newLog.setText("停止保存");
                save = true;
            }
        }
        initXlog();
    }

    void initXlog(){
        Log.i(TAG, "新建日志");
        //获取文件保存地址
        File file = getApplicationContext(). getExternalFilesDir(null);
        String path = file.getPath();
//        //配置XLog
//        LogConfiguration config = new LogConfiguration.Builder()
//                .logLevel(BuildConfig.DEBUG ? LogLevel.ALL// Specify log level, logs below this level won't be printed, default: LogLevel.ALL 指定日志级别，此级别以下的日志将不会打印，默认值:LogLevel.ALL
//                        : LogLevel.NONE)
//                .tag("MY_TAG") // Specify TAG, default: "X-LOG" 指定标签，默认:“X-LOG”
//                .enableThreadInfo() // Enable thread info, disabled by default 启用线程信息，默认禁用
//                .enableStackTrace(2) // Enable stack trace info with depth 2, disabled by default 启用深度为2的堆栈跟踪信息，默认禁用
//                .enableBorder() // Enable border, disabled by default 启用边框，默认禁用
//                .build();
//        Printer androidPrinter = new AndroidPrinter(true); // Printer that print the log using android.util.Log 使用android.util.Log打印日志的打印机
//        Printer consolePrinter = new ConsolePrinter(); // Printer that print the log to console using System.out 使用System.out将日志打印到控制台的打印机

        String filename = editText_filename.getText().toString();
        Log.i(TAG, filename);
        Printer filePrinter = new FilePrinter // Printer that print(save) the log to file 打印(保存)日志到文件的打印机
                .Builder(path) // Specify the directory path of log file(s) 指定日志文件的目录路径
                .fileNameGenerator(new myFileNameGenerator(filename)) // Default: ChangelessFileNameGenerator("log") 默认值:ChangelessFileNameGenerator(“日志”)
                .backupStrategy(new NeverBackupStrategy()) // Default: FileSizeBackupStrategy(1024 * 1024) 默认:FileSizeBackupStrategy(1024 * 1024)
                .build();
//        //初始化XLog
//        XLog.init( // Initialize XLog 初始化XLog
//                config, // Specify the log configuration, if not specified, will use new LogConfiguration.Builder().build() 指定日志配置，如果未指定，将使用新的LogConfiguration.Builder().build()
//                androidPrinter, // Specify printers, if no printer is specified, AndroidPrinter(for Android)/ConsolePrinter(for java) will be used. 指定打印机，如果没有指定打印机，AndroidPrinter(用于Android)/ConsolePrinter(用于java)将被使用。
//                consolePrinter,
//                filePrinter);

        XLog.init(LogLevel.ALL,filePrinter);
        // XLog.v(path);
        XLog.v("日志");
    }

    void run() throws IOException {

        // 获取系统服务得到UsbManager实例
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        //查找所有插入的设备
        List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);
        if (availableDrivers.isEmpty()) {
            return;
        }
        Log.i(TAG, "打开设备");
        // 打开设备，建立通信连接
        driver = availableDrivers.get(0);
        Log.i(TAG, driver.toString());
        connection = mUsbManager.openDevice(driver.getDevice());
        if (connection == null) {
            // You probably need to call UsbManager.requestPermission(driver.getDevice(), ..)
            Log.i(TAG, "失败");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
            mUsbManager.requestPermission(driver.getDevice(), pendingIntent);
        }
    }

    //开线程读取数据
    private void startReading() throws IOException {
//打开端口，设置端口参数，读取数据
        port = driver.getPorts().get(0);
        Log.i(TAG, String.format("port:%s",port.toString()));

        port.open(connection);

        usb_connect = true;

//四个参数分别是：波特率，数据位，停止位，校验位
        port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);


        boolean isReading = true;
        mReadingthread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isReading) {
                    synchronized (this) {
                        byte data_buffer[] = new byte[120];
                        int numBytesRead = 0;
                        try {
                            numBytesRead = port.read(data_buffer, 10000);
                            String s = new String(data_buffer);
//                            Log.i(TAG, s.trim());
//                            Log.i(TAG, "Read " + numBytesRead + " bytes.");

                            msg.obj = s;//可以是基本类型，可以是对象，可以是List、map等
                            mHandler.sendMessage(msg);
                            msg = new Message();

                        } catch (IOException e) {
                            Log.i(TAG, e.toString());
                            e.printStackTrace();
                        }
                    }
                }
                try {
                    port.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        mReadingthread.start();
    }

    private void send(String value) throws IOException {
        if(usb_connect)
            port.write(value.getBytes(), 10000);
    }
    public static float convertToFloat(String number, float defaultValue) {
        if (number.isEmpty()) {
            return defaultValue;
        }
        try {
            return Float.parseFloat(number);
        } catch (Exception e) {
            return defaultValue;
        }

    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    try {
                        String st = (String) msg.obj;
//                        print_Buffer.append(st);
//                        textView_print.setText(print_Buffer.toString());
                        String[] str_data_list = st.split("\t");
                        String str_datalength = editTextNumber_datalength.getText().toString();
                        String str_dataindex = editTextNumber_dataindex.getText().toString();
                        String str_dataindex2 = editTextNumber_dataindex2.getText().toString();

//                        String str_datalength = "0";
//                        String str_dataindex = "5";
//                        String str_dataindex2 = "17";

                        if(str_datalength.isEmpty() || str_dataindex.isEmpty() || str_dataindex2.isEmpty())
                            return;
                        int int_datalength = Integer.parseInt(str_datalength);
                        if (int_datalength == 0 || str_data_list.length >= int_datalength) {
                            int int_dataindex = Integer.parseInt(str_dataindex);
                            int int_dataindex2 = Integer.parseInt(str_dataindex2);
                            if(str_data_list.length>int_dataindex) {
//                                Log.i(TAG, "st_angle[int_dataindex]");
                                Log.i(TAG, str_data_list[int_dataindex]);
                                try {
                                    XLog.v("************");
                                    XLog.v(str_data_list);
                                    XLog.v(str_data_list[int_dataindex]);
                                }catch (Exception e){

                                }
                                textView_angle.setText(str_data_list[int_dataindex]+"m");

                            }
                            if(str_data_list.length>int_dataindex2) {
                                imageView_pointer.setRotation(convertToFloat(str_data_list[int_dataindex2], -90));
                                textView_angle2.setText(str_data_list[int_dataindex2]+"°");
                            }
                        }
                    } catch (Exception e) {
                        Log.i(TAG, e.toString());
                    }

                    break;
                default:
                    break;
            }
        }
    };
}